<template>
  <el-dialog
    destroy-on-close
    append-to-body
    title="分配权限"
    :visible.sync="isShow"
    width="50%"
  >
    <el-tree
      ref="tree"
      :data="tree"
      show-checkbox
      :default-checked-keys="selectedPermissions"
      :props="defaultProps"
      check-strictly
      node-key="value"
      default-expand-all
    >
    </el-tree>
    <span slot="footer" class="dialog-footer">
      <el-button @click="onClose()">取 消</el-button>
      <el-button type="primary" @click="onSave()">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { get, post } from "@/api/base.js";
export default {
  props: {
    tree: {
      type: Array,
    },
  },
  data() {
    return {
      isShow: false,
      roleId: null,
      treeData: [],
      selectedPermissions: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
    };
  },
  methods: {
    open(roleId) {
      this.roleId = roleId;
      this.getRoles(roleId);
      this.isShow = true;
    },
    onSave() {
      let keys = this.$refs["tree"].getCheckedKeys();
      post("assign-permission", {
        role_id: this.roleId,
        permission_ids: keys,
      }).then((res) => {
        this.$message.success(res.message);
      });
      this.isShow = false;
    },
    onClose() {
      this.isShow = false;
      this.selectedPermissions = [];
    },
    getRoles(roleId) {
      get(`role/${roleId}/permissions`).then((res) => {
        this.selectedPermissions = res.data.permissions;
      });
    },
  },
};
</script>